<template>
  <div class="list">
    <div
      :class="{item,on:index==checkedIndex}"
      v-for="(item,index) in letters"
      :key="item"
      :ref="item"
      @click="handleLetterClick(index)"
      @touchstart.prevent="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
    >{{item}}</div>
  </div>
</template>
<script type='text/babel'>
export default {
  props: {
    cities: Object,
    listIndex: Number
  },
  data () {
    return {
      touchStauts: false,
      firstTop: 0,
      timer: null,
      checkedIndex: 0
    }
  },
  created () {
  },
  updated () {
    this.firstTop = this.$refs['A'][0].offsetTop
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  methods: {
    handleLetterClick (index) {
      this.$emit('change', index)
      this.checkedIndex = index
    },
    handleTouchStart (e) {
      this.touchStauts = true
    },
    handleTouchMove (e) {
      if (this.touchStauts) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          let firstTop, thisTop, distance, thisLetter
          firstTop = this.firstTop
          thisTop = e.touches[0].clientY - 84
          distance = thisTop - firstTop
          thisLetter = Math.floor(distance / 20)
          if (thisLetter >= 0 && thisLetter < this.letters.length) {
            this.$emit('change', thisLetter)
            this.checkedIndex = thisLetter
          }
        }, 16)
      }
    },
    handleTouchEnd (e) {
      this.touchStauts = false
    }
  },
  components: {},
  watch: {
    listIndex () {
      this.checkedIndex = this.listIndex
    }
  }
}
</script>
<style scoped lang="scss" rel="stylesheet/scss">
  @import "../../../assets/styles/variable";
  .list{
    position: absolute;
    top:1.68rem;
    right:0;
    bottom: 0;
    /*background: red;*/
    width:.4rem;
    text-align: center;
    display: flex;
    flex-direction: column;
    justify-content:center;
    .item{
      line-height:.4rem;
      text-align: center;
      color: $bgColor1;
      &.on{
        color: red;
      }
    }
  }
</style>
